package com.xxxcompany.wordbook.dao;

import java.sql.*;

import com.xxxcompany.utils.DbUtils;
import com.xxxcompany.wordbook.entity.User;

public class UserDAOImpl implements IUserDAO {

	@Override
	public int insert(User user) throws SQLException {
		//
		Connection conn = DbUtils.getConnection();
		//
		String sql = "insert into user value(null,?,?,?,?);";
		PreparedStatement stmt = conn.prepareStatement(sql);

		stmt.setString(1, user.getUsername());
		stmt.setString(2, user.getPassword());
		stmt.setString(3, user.getNickname());
		stmt.setString(4, user.getEmail());

		int result = stmt.executeUpdate();

		DbUtils.destoryResource(conn, stmt, null);

		return result;
	}

	@Override
	public User find(String username, String password) throws SQLException {
		//
		Connection conn = DbUtils.getConnection();
		//
		String sql = "select * from user where username=? and password=?;";
		PreparedStatement stmt = conn.prepareStatement(sql);

		stmt.setString(1,username);
		stmt.setString(2,password);

		ResultSet rs = stmt.executeQuery();
		
		User user = null;
		if(rs.next())
		{
			int id = rs.getInt("id");
			String nickname = rs.getString("nickname");
			String email = rs.getString("email");
			user = new User(id,username,password,nickname,email);
		}

		DbUtils.destoryResource(conn, stmt, null);

		return user;
	}

}